package com.fw.ui.view.event;

import java.util.concurrent.TimeoutException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.fw.ui.bao.MessageBAO;
import com.vaadin.event.FieldEvents.TextChangeEvent;
import com.vaadin.event.FieldEvents.TextChangeListener;
import com.vaadin.server.Page;
import com.vaadin.ui.Notification;

public abstract class AbstractTextChangeListener extends AbstractListener implements TextChangeListener {

    private static final long serialVersionUID = -8750847762824735L;

    @Autowired
    private MessageBAO messageBAO;
    
    @Override
    public void textChange(TextChangeEvent event) {
	Logger log = LoggerFactory.getLogger(this.getClass());
	try {
	    if (this.filter()) {
		return;
	    }
	    if (this.validate(event)) {
		log.info("VALIDATE EVENT TEXT CHANGE LISTENER [RESULT:TRUE]");
		log.info("EXECUTE EVENT TEXT CHANGE LISTENER START");
		this.change(event);
		log.info("EXECUTE EVENT TEXT CHANGE LISTENER FINISH");
	    } else {
		log.info("VALIDATE EVENT TEXT CHANGE LISTENER [RESULT:FALSE]");
	    }
	} catch (TimeoutException e) {
	    log.error("EVENT TEXT CHANGE LISTENER ERROR [" + e.getMessage() + "]");
	    e.printStackTrace();
	    String msg = this.messageBAO.getMessage("message.error.timeout");
	    Notification notification = new Notification("Warning", msg, Notification.Type.WARNING_MESSAGE, true);
	    notification.setDelayMsec(1000);
	    notification.show(Page.getCurrent());
	} catch (Exception e) {
	    log.error("EVENT TEXT CHANGE LISTENER ERROR [" + e.getMessage() + "]");
	    e.printStackTrace();
	    String msg = this.messageBAO.getMessage("message.error.common");
	    Notification notification = new Notification("Warning", msg, Notification.Type.WARNING_MESSAGE, true);
	    notification.setDelayMsec(1000);
	    notification.show(Page.getCurrent());
	}
    }

    public abstract boolean validate(TextChangeEvent event) throws Exception;

    public abstract void change(TextChangeEvent event) throws Exception;

}
